<?php

class TarjetaController extends Zend_Controller_Action
{

    public function init(){
        $this->em = Zend_Registry::getInstance()->entitymanager;
    }

    public function indexAction(){
        $profesores = $this->em->createQueryBuilder()
                           ->select    ('p.idProfesor')
                           ->addselect ('p.codigoTarjeta')
                           ->addselect ('u.nombre')
                           ->addselect ('u.apellido')
                           ->from      ('Default_Model_Profesor', 'p')
                           ->join      ('p.usuario', 'u')
                           ->orderBy   ('u.apellido', 'asc')
                           ->getQuery  ()
                           ->execute   ();

        $this->view->profesores = Zend_Json::encode(Array(
            "success" => true,
            "total"   => count($profesores),
            "rows"    => $profesores
        ));
    }

    public function ajaxGenerarAction(){

        $profesores = $this->_request->getPost('profesores');
        $tipo = $this->_request->getPost('tipo');

        //var_dump($profesores);return;

        function widthForStringUsingFontSize($string, Zend_Pdf_Resource_Font $font, $fontSize){
            $drawingString = iconv('', 'UTF-16BE', $string);
            $characters = array();
            for ($i = 0; $i < strlen($drawingString); $i++) {
                $characters[] = (ord($drawingString[$i++]) << 8) | ord($drawingString[$i]);
            }
            $glyphs = $font->glyphNumbersForCharacters($characters);
            $widths = $font->widthsForGlyphs($glyphs);
            $stringWidth = (array_sum($widths) / $font->getUnitsPerEm()) * $fontSize;
            return $stringWidth;
        }

        //Algoritmo de Myriam para modificar codigo al generar nueva tarjeta
        function actualizar($codigo){
            $i=0;
            $var1[] = str_split($codigo, 5);
            $var2[] = str_split($codigo);
            $cod1=$var2[0][5];
            $cod2=$var2[0][6];

            $alfabeto[]=str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
            if($cod1=="Z"){
                    $cod3="AA";
            }
            if($cod2=="Z"){
                for($j=0;$j<=27;$j=$j+1){
                    if($cod1==$alfabeto[0][$i]){
                        $cod1=$alfabeto[0][$i+1];
                        break;
                    }
                }
            }else{
                for ($i=0;$i<=27;$i=$i+1){
                    if($cod2==$alfabeto[0][$i]){
                        $cod2=$alfabeto[0][$i+1];
                        break;
                    }
                }
            }
            $cod=''.$var1[0][0].''.$cod1.''.$cod2.'XXXXX';
            return $cod;
	}

        $rows = Zend_Json::decode($profesores);

        //var_dump($rows);return;

        $pdf = new Zend_Pdf();

        //Definir fuentes
        $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);

        $logo = \Zend_Pdf_Image::imageWithPath('img/UCA2.png');

        $adjust = 150;

        $profCount = 0;
        $gen = false;

        foreach($rows as $row){

            if($profCount == 0){
                $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4); //'842:595:'
                //Agregar pagina al pdf
                $pdf->pages[] = $page;
            }

            $prof = $this->em->createQueryBuilder()
                             ->select    ('p.idProfesor')
                             ->addselect ('p.codigoTarjeta')
                             ->addselect ('u.nombre')
                             ->addselect ('u.apellido')
                             ->from      ('Default_Model_Profesor', 'p')
                             ->join      ('p.usuario', 'u')
                             ->where     ("p.idProfesor='".$row."'")
                             ->orderBy   ('u.apellido', 'asc')
                             ->getQuery  ()
                             ->execute   ();

            $nombre = $prof[0]['nombre'].' '.$prof[0]['apellido'];

            //si tipo es generar
            $codigo = $prof[0]['codigoTarjeta'];

            //Si se reimprime (tipo 1) el codigo se mantiene
            if($tipo==1){
                $codigo = $prof[0]['codigoTarjeta'];
            }
            //Si se genera (tipo 0) se debe actualizar el codigo
            else{
                //Se actualiza el codigo de tarjeta
                $codigo = actualizar($prof[0]['codigoTarjeta']);
                $profesor = $this->em->find('Default_Model_Profesor', $row);
                $profesor->setCodigoTarjeta($codigo);
                $this->em->persist($profesor);
            }

            $totalAdjust = $profCount*$adjust;

            $page->drawImage($logo, 175, 746-$totalAdjust, 215, 786-$totalAdjust);
            $page->setLineColor(new \Zend_Pdf_Color_Rgb(0,0,0))
                     ->drawLine(90, 820-$totalAdjust, ($page->getWidth()-90), 820-$totalAdjust)
                     ->drawLine(90, 685-$totalAdjust, ($page->getWidth()-90), 685-$totalAdjust)
                     ->drawLine(90, 820-$totalAdjust, 90, 685-$totalAdjust)

                     ->drawLine(($page->getWidth()-90), 820-$totalAdjust, ($page->getWidth()-90), 685-$totalAdjust)
                     ->drawLine(351.25, 720-$totalAdjust, 451.25, 720-$totalAdjust)
                     ->drawLine(297.5, 820-$totalAdjust, 297.5, 685-$totalAdjust);

            $page->setFont($font, 7)
                     ->drawText('Control interno de profesores', 356, 805-$totalAdjust)
                     ->drawText('Este documento no posee validez legal', 340, 795-$totalAdjust)
                     ->drawText('En caso de extravío de este documento,', 341, 775-$totalAdjust, 'UTF-8')
                     ->drawText('favor informar al tel. 334-650, interno 125', 338.5, 765-$totalAdjust)
                     ->drawText('Autorizado por:', 377.5, 710-$totalAdjust)
                     ->drawText('Director Académico', 371, 700-$totalAdjust, 'UTF-8');

            $page->setFont($font, 10)
                     ->drawText('UNIVERSIDAD CATÓLICA', 133.5, 800-$totalAdjust, 'UTF-8');

            $nombreWidth = widthForStringUsingFontSize($nombre, $font, 7);
            $codWidth = widthForStringUsingFontSize($codigo, $font, 7);

            $xPosNombre = 90 + ((207.5 - $nombreWidth)/2);
            $xPosCod = 90 + ((207.5 - $nombreWidth)/2);

            $page->setFont($font, 7)
                     ->drawText('Nuestra Señora de la Asunción', 147, 790-$totalAdjust, 'UTF-8')
                     ->drawText($nombre, $xPosNombre, 735-$totalAdjust, 'UTF-8');
                 //    ->drawText($codigo, $xPosCod, 745-$totalAdjust, 'UTF-8');

            $barcodeOptions = array('text' => '*'.$codigo.'%', 'drawText' => FALSE, 'font' => 1,
                    'withQuietZones' => FALSE,  'barHeight' => 35);

            $bc = Zend_Barcode::factory(
                    'code128',
                    'image',
                    $barcodeOptions,
                    array()
            );

            // @var $bc Zend_Barcode
            $res = $bc->draw();
            $filename = getcwd() .'/img/barcodes/tarjeta.png';

            $gen = imagepng($res, $filename);

            $image = \Zend_Pdf_Image::imageWithPath('img/barcodes/tarjeta.png');
            $page->drawImage($image, 99, 695-$totalAdjust, $image->getPixelWidth()+99, $image->getPixelHeight()+695-$totalAdjust);

            $profCount = ($profCount+1)%5;

        }

        //Si las tarjetas fueron generadas
        if($tipo==0){
            $this->em->flush();
        }

        // Guardar el pdf
        $fileName = 'Tarjeta.pdf';
        $pdf->save($fileName);

        if($gen)
            X\Msg::Success('El reporte se ha generado con éxito.');
        else
            X\Msg::Success('Error al generar el código.');

    }

    public function pdfAction(){

          $pdf = Zend_Pdf::load('Tarjeta.pdf');

          $this->getResponse()->setHeader('Content-type', 'application/x-pdf', true);
          $this->getResponse()->setHeader('Content-disposition', "filename=Tarjeta.pdf", true);
          $this->getResponse()->setBody($pdf->render());
     }

}

